package service

import (
	"fanqiechaodan-blog/config"
	"fanqiechaodan-blog/dao"
	"fanqiechaodan-blog/models"
	"fanqiechaodan-blog/utils"
	"html/template"
)

func GetPostByCategoryId(cid, page, pageSize int) (*models.CategoryResponse, error) {
	categorys, err := dao.GetAllCategory()
	if err != nil {
		return nil, err
	}
	postPage, err := dao.PostPageByCategoryId(cid, page, pageSize)
	if err != nil {
		return nil, err
	}
	categoryName, err := dao.GetCategoryNameById(cid)
	if err != nil {
		return nil, err
	}
	var posts []models.PostMore
	for _, post := range postPage {
		// 将内容转换成中文,首页内容只展示部分内容
		// 去除HTML标签
		contentStr := utils.StripHTML(post.Content)
		content := []rune(contentStr)
		if len(content) > 100 {
			content = content[0:100]
		}
		// 获取分类名
		categoryName, err := dao.GetCategoryNameById(post.CategoryId)
		if err != nil {
			return nil, err
		}
		userName, err := dao.GetUserNameById(post.UserId)
		if err != nil {
			return nil, err
		}
		postMore := models.PostMore{
			Pid:          post.Pid,
			Title:        post.Title,
			Slug:         post.Slug,
			Content:      template.HTML(content),
			CategoryId:   post.CategoryId,
			CategoryName: categoryName,
			UserId:       post.UserId,
			UserName:     userName,
			ViewCount:    post.ViewCount,
			Type:         post.Type,
			CreateAt:     models.DateDay(post.CreateAt),
			UpdateAt:     models.DateDay(post.UpdateAt),
		}
		posts = append(posts, postMore)
	}
	count, err := dao.PostCountByCategoryId(cid)
	if err != nil {
		return nil, err
	}
	var pages []int
	pageCount := (count-1)/pageSize + 1
	for i := 1; i <= pageCount; i++ {
		pages = append(pages, i)
	}
	return &models.CategoryResponse{
		HomeResponse: &models.HomeResponse{
			Viewer:    config.Cfg.Viewer,
			Categorys: categorys,
			Posts:     posts,
			Total:     count,
			Page:      page,
			Pages:     pages,
			PageEnd:   page != pageCount,
		},
		CategoryName: categoryName,
	}, err
}
